package cn.yzgy.yzgyoa.common.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.TimeUnit;


/**
 * Redis小工具
 * @author Yqsen
 * @version 0.0.2
 * @since 2019-08-1
 */
@Component
public class RedisUtils {
    private final StringRedisTemplate redisTemplate;

    public RedisUtils(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 某键自增
     *
     * @param key      键名
     * @param liveTime 有效时长
     * @return 增加增加后的值
     */
    public long incr(String key, int liveTime) {
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, Objects.requireNonNull(redisTemplate.getConnectionFactory()));
        long increment = entityIdCounter.incrementAndGet();
        //初始设置过期时间
        if (increment <= 1 && liveTime > 0) {
            entityIdCounter.expire(liveTime, TimeUnit.SECONDS);
        }
        return increment;
    }
}